//
// Created by sgyt on 2019/12/21.
// pread,pwrite 的列子：
// 1.不会更新当前文件的偏移量
// 2.调用pread时，无法中断其定位和读操作
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc,char *argv[])
{
    //创建sgyt1.txt的文件，并赋予最高的权限
    int fd = open("sgyt.txt",O_RDWR|O_CREAT,0777);
    //写入数据
    char buf[]  = "hello world!\n";
    int num = write(fd,buf, sizeof(buf));
    printf("write ok\n");


    //获取当前文件的偏移值
    int offset = lseek(fd,0,SEEK_CUR);
    printf("num = %d,offset = %d\n",num,offset);

    //pwrite去写入数据
    char buf2[] = "my best friend!\n";
    pwrite(fd,buf2,strlen(buf2),6);
    int offset1 = lseek(fd,0,SEEK_CUR);
    //这里看出pwrite的时候文件偏移值没有变化，从第一次的14，使用pwrite写完数据后，偏移值没改变
    printf("offset1 = %d\n",offset1);

    //再此获取当前的偏移值
    char readbuf1[1024],readbuf2[1024];
    memset(readbuf1, sizeof(readbuf1),0x00);
    int ret = read(fd,readbuf1, sizeof(readbuf1));
    offset1 = lseek(fd,0,SEEK_CUR);
    printf("ret = %d,offset1 = %d\n",ret,offset1);


    //使用pread的读取
    memset(readbuf2, sizeof(readbuf2),0x00);
    pread(fd,readbuf2,sizeof(readbuf2),6);
    printf("readbuf1 = %s,readbuf2 = %s\n",readbuf1,readbuf2);

    close(fd);
    return 0;
}

